import React, { useState, useEffect } from 'react'
import { Menu, Icon } from 'antd'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import MENU from './constants'
import { actionCreators } from '../../store'
import { actionCreators as orderActionCreators } from '../../pages/order/store'
import { ROLE_ADMIN } from '../../constants'
import './style.scss'

function AppMenu(props) {
  const { menuCollapsed, setBreadcrumb, setCurrentPage, loginUser } = props
  const [defaultSelected, setDefaultSelected] = useState([])
  const [defaultOpen, setDefaultOpen] = useState([])
  const [openKeys, setOpenKeys] = useState([])
  const [menuList, setMenuList] = useState([])

  useEffect(() => {
    if (loginUser && loginUser.role_id) {
      const menuList = initMenuList(MENU, loginUser.role_id)
      setMenuList(menuList)
    }
  }, [loginUser])

  useEffect(() => {
    const { pathname } = props.location
    if (!menuList.length) {
      return
    }
    // 根据url获取当前应该展开和选中的菜单
    let probableParentMenu = null
    const getActiveKey = (menuList, path, parentKey) => {
      for (const menu of menuList) {
        if (menu.path === path) {
          return { key: menu.key, label: menu.label, parentKey }
        }
        if (path.indexOf(menu.path) > -1) {
          if (!probableParentMenu || probableParentMenu.path.length < menu.path.length) {
            probableParentMenu = { key: menu.key, label: menu.label, parentKey, path: menu.path }
          }
        }
        if (menu.children) {
          const selected = getActiveKey(menu.children, path, menu.key)
          if (selected) {
            return selected
          }
        }
      }
      return false
    }
    // 获取选中和展开的菜单
    const selectedMenu = getActiveKey(menuList, pathname, '/') || probableParentMenu
    const cachedActiveMenu = JSON.parse(sessionStorage.getItem('lfp-backend-active-menu') || '{}')
    let key = cachedActiveMenu.key || '/' // 默认选中菜单项(一级或二级菜单)
    let openKey = cachedActiveMenu.openKey || '/' // 默认展开菜单(一级菜单)
    if (selectedMenu) {
      key = selectedMenu.key
      openKey = selectedMenu.parentKey
      sessionStorage.setItem('lfp-backend-active-menu', JSON.stringify({ openKey, key, label: selectedMenu.label }))
    }
    setBreadcrumb(selectedMenu ? selectedMenu.label : (cachedActiveMenu ? cachedActiveMenu.label : ''))
    setDefaultOpen([openKey])
    setDefaultSelected([key])
    if (openKeys.indexOf(openKey) === -1) {
      setOpenKeys([openKey])
    }
  }, [props.location.pathname, menuList])

  const initMenuList = (menuList, roleId) => {
    if (roleId === ROLE_ADMIN) { // 管理页
      return menuList
    }
    return menuList.filter(menu => {
      if (menu.allowRoles && menu.allowRoles.indexOf(roleId) === -1) {
        return false
      }
      if (menu.children) {
        menu.children = menu.children.filter(subMenu => (!subMenu.allowRoles || subMenu.allowRoles.indexOf(roleId) > -1))
      }
      return true
    })
  }

  const onMenuClick = menu => {
    const { path } = menu.item.props
    setCurrentPage(1)
    props.history.push(path)
  }

  const onMenuChange = keys => {
    const lastOpenKey = keys.find(key => openKeys.indexOf(key) === -1)
    if (!menuList.find(menu => menu.key === lastOpenKey)) {
      setOpenKeys(keys)
    } else {
      setOpenKeys(lastOpenKey ? [lastOpenKey] : [])
    }
  }

  return (
    <div className={menuCollapsed ? 'app-menu' : 'app-menu app-menu--collapsed'}>
      {defaultSelected.length > 0 && defaultOpen.length > 0 && (
        <Menu
          defaultSelectedKeys={defaultSelected}
          defaultOpenKeys={defaultOpen}
          selectedKeys={defaultSelected}
          openKeys={openKeys}
          mode="inline"
          theme="dark"
          inlineCollapsed={menuCollapsed}
          onClick={onMenuClick}
          onOpenChange={onMenuChange}
          style={{ height: '100%' }}
        >
          <header>
            {!menuCollapsed && (
              <span>订单管理系统</span>
            )}
          </header>
          {menuList.map(menu => {
            return (
              menu.children
                ? (
                  <Menu.SubMenu
                    key={menu.key}
                    title={
                      <span>
                        <Icon type={menu.icon}/>
                        <span>{menu.label}</span>
                      </span>
                    }
                  >
                    {menu.children.map(sub => {
                      return (
                        <Menu.Item key={sub.key} path={sub.path}>
                          {sub.label}
                        </Menu.Item>
                      )
                    })}
                  </Menu.SubMenu>
                ) : (
                  <Menu.Item key={menu.key} path={menu.path}>
                    <Icon type={menu.icon}/>
                    <span>{menu.label}</span>
                  </Menu.Item>
                )
            )
          })}
        </Menu>
      )}
    </div>
  )
}

export default connect(state => ({
  menuCollapsed: state.getIn(['common', 'menuCollapsed']),
  loginUser: state.getIn(['common', 'loginUser'])
}), dispatch => ({
  setBreadcrumb(value) {
    dispatch(actionCreators.setBreadCrumb(value))
  },
  setCurrentPage(value) {
    dispatch(orderActionCreators.setCurrentPage(value))
  }
}))(withRouter(AppMenu))
